//
//  ECMineSettingViewController.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/11.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECMineSettingViewController.h"
#import "ECUIVC_Login.h"
#import "CYAnimation.h"
#import "SUPlayer.h"

#import "ECMineAboutMeViewController.h"

@interface ECMineSettingViewController (){
    UILabel *cachedLab;
    ///开关
    UISwitch *switchBtn;
    ///退出登录按钮
    ECUButton *loginOutBtn;
}

@end

@implementation ECMineSettingViewController

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    DLog(@"%@",[[UserInfoManager shareUser]token]);
}


-(void)addSubviews{
    UILabel *netTypeLab = [[UILabel alloc]init];
    [self.view addSubview:netTypeLab];
    netTypeLab.text = @"允许2G/3G/4G网络观看视频";
    netTypeLab.font = [UIFont systemFontOfSize:16.f];
    netTypeLab.textColor = [UIColor colorWithHexString:@"#333333"];
    
    switchBtn = [[UISwitch alloc]init];
    [self.view addSubview: switchBtn];
    [switchBtn addTarget:self action:@selector(switchClick:) forControlEvents:UIControlEventValueChanged];
    
    //调取本地记录(应该与本账号进行绑定)
    int isOpen = [[[NSUserDefaults standardUserDefaults] objectForKey:@"switchButtonStatus"] intValue];
    switchBtn.on = isOpen;
    
    UIView *lineView_one = [[UIView alloc]init];
    [self.view addSubview:lineView_one];
    lineView_one.backgroundColor = [UIColor colorWithHexString:@"#EBEBEB"];
    
    ECUButton *clearBtn = [[ECUButton alloc]init];
    [self.view addSubview:clearBtn];
    clearBtn.tag = 10;
    [clearBtn setTitle:@"清除缓存" forState:0];
    clearBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
    clearBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [clearBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:0];
    [clearBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cachedLab = [[UILabel alloc]init];
    [self.view addSubview:cachedLab];
    cachedLab.textAlignment = NSTextAlignmentRight;
    cachedLab.font = [UIFont systemFontOfSize:16.f];
    cachedLab.text = [NSString stringWithFormat:@"%.1fM",[self folderSize]];
    cachedLab.textColor = [UIColor colorWithHexString:@"#999999"];
    
    UIView *lineView_two = [[UIView alloc]init];
    [self.view addSubview:lineView_two];
    lineView_two.backgroundColor = [UIColor colorWithHexString:@"#EBEBEB"];
    
    ECUButton *aboutBtn = [[ECUButton alloc]init];
    [self.view addSubview:aboutBtn];
    aboutBtn.tag = 11;
    [aboutBtn setTitle:@"关于我们" forState:0];
    aboutBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
    aboutBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [aboutBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:0];
    [aboutBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *lineView_three = [[UIView alloc]init];
    [self.view addSubview:lineView_three];
    lineView_three.backgroundColor = [UIColor colorWithHexString:@"#EBEBEB"];
    
    loginOutBtn = [[ECUButton alloc]init];
    [self.view addSubview:loginOutBtn];
    loginOutBtn.tag = 12;
    [loginOutBtn setTitle:@"退出登录" forState:0];
    loginOutBtn.layer.masksToBounds = YES;
    loginOutBtn.layer.cornerRadius = 3.f;
    loginOutBtn.layer.borderWidth = 1.f;
    loginOutBtn.layer.borderColor = [UIColor colorWithHexString:@"#ff6700"].CGColor;
    [loginOutBtn setTitleColor:[UIColor colorWithHexString:@"#ff6700"] forState:0];
    [loginOutBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    if (![[UserInfoManager shareUser]token]) {
        loginOutBtn.hidden = YES;
    }
    
    WeakSelf(weakSelf);
    [netTypeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(kProportion_Height(60));
        make.left.equalTo(weakSelf.view.mas_left).offset(kProportion_Width(45));
        make.right.equalTo(weakSelf.view.mas_right).offset(-kProportion_Width(200));
        make.height.equalTo(@18);
    }];
    
    [switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view.mas_right).offset(-kProportion_Width(45));
        make.centerY.equalTo(netTypeLab.mas_centerY);
    }];
    
    [lineView_one mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(kProportion_Height(164));
        make.left.equalTo(netTypeLab.mas_left);
        make.right.equalTo(switchBtn.mas_right);
        make.height.equalTo(@1);
    }];
    
    [clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView_one.mas_bottom);
        make.left.equalTo(netTypeLab.mas_left);
        make.right.equalTo(switchBtn.mas_right);
        make.height.equalTo(@(kProportion_Height(164)));
    }];
    
    [cachedLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(clearBtn.mas_centerY);
        make.right.equalTo(switchBtn.mas_right);
        make.width.equalTo(@100);
    }];
    
    [lineView_two mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(clearBtn.mas_bottom);
        make.left.equalTo(lineView_one.mas_left);
        make.width.equalTo(lineView_one.mas_width);
        make.height.equalTo(@1);
    }];
    
    [aboutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView_two.mas_bottom);
        make.left.equalTo(clearBtn.mas_left);
        make.right.equalTo(clearBtn.mas_right);
        make.height.equalTo(clearBtn.mas_height);
    }];
    
    [lineView_three mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(aboutBtn.mas_bottom);
        make.left.equalTo(lineView_one.mas_left);
        make.right.equalTo(lineView_one.mas_right);
        make.height.equalTo(@1);
    }];
    
    [loginOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-kProportion_Height(36)-kSafeAreaBottomHeight);
        make.width.equalTo(@(kProportion_Width(960)));
        make.height.equalTo(loginOutBtn.mas_width).multipliedBy(126.f/960.f);
    }];
    
    
}

/*  按钮点击事件  */
-(void)btnClick:(ECUButton *)btn{
    switch (btn.tag) {
        case 10:{//清除缓存
            [self removeCache];
        }
            break;
        case 11:{//关于我们
            ECMineAboutMeViewController *vc = [[ECMineAboutMeViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 12:{//退出登录
            [self logoutOfAccount];
        }
            break;
        default:
            break;
    }
}

// 开关事件切换通知
-(void)switchClick:(UISwitch *)btn{
    int isButtonOn;
    if ([btn isOn]) {
        isButtonOn = 1;
    }else{
        isButtonOn = 0;
    }
    
    
    [[NSUserDefaults standardUserDefaults] setObject:@(isButtonOn) forKey:@"switchButtonStatus"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


// 缓存大小
- (CGFloat)folderSize{
    CGFloat folderSize = 0.0;
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
    //获取所有文件的数组
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    DLog(@"文件数：%ld",files.count);
    for(NSString *path in files) {
        NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
        //累加
        folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1000.0/1000.0;
    return sizeM;
}

- (void)removeCache{
    //===============清除缓存==============
    //获取路径
    NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    //返回路径中的文件数组
    NSArray*files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError*error;
        NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager]fileExistsAtPath:path]){
            BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            if(isRemove) {
                [MBProgressHUD showTipMessageInWindow:@"清除成功"];
                cachedLab.text = @"0M";
                
                ///清除音频缓存数据
                [SUPlayer clearCache];
            }else{
                DLog(@"清除失败");
            }
        }
    }
}


/**
 退出登录接口
 */
-(void)logoutOfAccount{
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_POST_Logout
                           params:@{
                                    @"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]
                                    }
                          headers:nil
                          success:^(id json) {
                          }
                          failure:^(NSError *error) {
                          }];
    [self exitAccount];
}

-(void)exitAccount{
    [MBProgressHUD showTipMessageInWindow:@"退出成功"];
    
    loginOutBtn.hidden = YES;
    [UserInfoManager loginOut];
    //发送退出登录通知
    NSNotification *notification =[NSNotification notificationWithName:kNotifactionUserLogout object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
